package net.wsfcp.android.ui.view.main.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import net.wsfcp.android.R;
import net.wsfcp.android.base.BaseFragment;
import net.wsfcp.android.base.BasePresenter;
import net.wsfcp.android.event.OpenMenuEvent;
import net.wsfcp.android.ui.widget.SwipeWebView;
import net.wsfcp.android.utils.CommonValue;

import org.greenrobot.eventbus.EventBus;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

//主页fragment&H5fragment
public class MainFragment extends BaseFragment {
    @BindView(R.id.web)
    SwipeWebView web;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;


    String url = "http://www.baidu.com";

    Map<String, String> headerMap = new HashMap<>();//添加请求头区分是否app内调用

    public WebView getWeb() {
        return web;
    }

    public void setUrl(String url) {
        this.url = url;
    }


    @Override
    protected BasePresenter loadPresenter() {
        return null;
    }

    @Override
    protected void initData() {
        headerMap.put(CommonValue.WEBVIEW_HEADER_KEY, CommonValue.WEBVIEW_HEADER_VALUE);
        syncCookie(getContext(), url);
        web.loadUrl(url, headerMap);//加载url
    }

    @Override
    protected void initListener() {
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                web.reload();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        swipe.setRefreshing(false);
                    }
                }, 3000);

            }
        });


    }

    @Override
    protected void initView() {
        //设置为可调用js方法
        web.getSettings().setJavaScriptEnabled(true);
        web.addJavascriptInterface(new JavaScriptinterface(getContext(), web), CommonValue.JS_METHOD);
        web.setWebViewClient(webViewClient);
        web.setWebChromeClient(new MyWebChrome());

        web.setSwipe(swipe);//解决滑动冲突

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_web;
    }

    @Override
    protected void otherViewClick(View view) {

    }


    public class JavaScriptinterface {
        Context context;

        public JavaScriptinterface(Context c, WebView mWebView) {
            context = c;
        }

        /**
         * 与js交互时用到的方法，在js里直接调用的(window.wsfcpJS.getMsg(str))
         */
        @JavascriptInterface
        public void getMsg(String str) {


//            String string = "原生给JS的数据";
//            call = "javascript:showMsg(\"" + string + "\")";
//            mWebView.post(new Runnable() {
//                @Override
//                public void run() {
//
//                    mWebView.loadUrl(call);
//                }
//            });

        }


        @JavascriptInterface
        public void openMenu() {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new OpenMenuEvent());
                }
            });
        }

    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
//            progressBar.setVisibility(View.GONE);
            swipe.setRefreshing(false);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
//            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

//不跳转到浏览器
            view.loadUrl(url, headerMap);
            return true;


        }

    };


    private class MyWebChrome extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                swipe.setRefreshing(false);
                progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                progressBar.setProgress(newProgress);//设置进度值
            }
        }
    }


    /**
     * 给WebView同步Cookie
     *
     * @param context 上下文
     * @param url     可以使用[domain][host]
     */
    private void syncCookie(Context context, String url) {

        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(context);
        }
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, CommonValue.WEBVIEW_HEADER_KEY + "=" + CommonValue.WEBVIEW_HEADER_VALUE);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.getInstance().sync();
        } else {
            CookieManager.getInstance().flush();
        }
    }

}
